﻿using Gx.Common;
using Gx.Common.Core;
using Gx.Dal;
using Gx.Dal.Manage;
using Gx.Dal.Shared;
using Gx.Model;
using Gx.Model.Entity;
using Gx.Model.Enums;
using Gx.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;


namespace Gx.Bll.Manage
{
    public class LKWarehouseEntryBll
    {

        protected LKWarehouseEntryDal dal = new LKWarehouseEntryDal();
        protected BaseDal<LKWarehouseEntryDetail> detailDal = new BaseDal<LKWarehouseEntryDetail>();
        protected BaseDal<LKWarehouseEntryCost> costDal = new BaseDal<LKWarehouseEntryCost>();
        protected BaseDal<LKGoodsCodes> codeDal = new BaseDal<LKGoodsCodes>();
        protected LKAttachmentBll attachmentBll = new LKAttachmentBll();

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedList<LKWarehouseEntry> GetLKWarehouseEntryPageList(LKWarehouseEntryInput input)
        {
            return dal.GetLKWarehouseEntryPageList(input);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public List<LKWarehouseEntry> GetLKWarehouseEntrys()
        {
            return dal.GetAll().ToList();
        }

        /// <summary>
        /// 新增商品入库单
        /// </summary>
        /// <param name="lKWarehouseEntryDto"></param>
        /// <returns></returns>
        public ReturnModel AddLKWarehouseEntry(LKWarehouseEntryDto lKWarehouseEntryDto)
        {
            string maxCode = dal.GetMaxLKWarehouseEntryCode();
            string code = "R" + DateTime.Now.ToString("yyMMdd") + "001";
            if (!string.IsNullOrWhiteSpace(maxCode))
            {
                //获取240716023月份，07为月份
                var maxMonth = maxCode.Substring(2, 2);
                var nowMonth = DateTime.Now.ToString("MM");
                if (maxMonth == nowMonth)
                {
                    int num = Convert.ToInt32(maxCode);//Convert.ToInt32(maxCode.Substring(7, 3));
                    num++;
                    code = "R" + num.ToString();//DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(3, '0');
                }

            }
            lKWarehouseEntryDto.WarehouseEntry.BillNo = code;
            lKWarehouseEntryDto.WarehouseEntry.CreateTime = DateTime.Now;
            lKWarehouseEntryDto.WarehouseEntry.CreateUserId = LoginHelper.GetUserId();
            lKWarehouseEntryDto.WarehouseEntry.CreateUser = LoginHelper.UserName();
            lKWarehouseEntryDto.WarehouseEntry.CompanyId = UserContext.CompanyId;



            var result = dal.AddLKWarehouseEntry(lKWarehouseEntryDto);//dal.Insert(lKWarehouseEntry);

            if (result && lKWarehouseEntryDto.AttachmentId > 0)
            {
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = lKWarehouseEntryDto.AttachmentId,
                    BillNo = code,
                    BillType = (int)BillTypeTemplate.WarehouseEntry,
                });
            }

            return new ReturnModel { Success = result, Msg = result ? "新增成功" : "新增失败" };
        }

        //新增商品明细
        public LKGoodsCodes AddLKWarehouseEntryDetailGoodsCode()
        {
            var codes = new LKGoodsCodes();
            //商品规格编码 P2400601 P+年+0+月+两位位流水号
            string maxGoodsCode = dal.GetMaxLKWarehouseEntrySpecCode();
            string goodsCode = "P" + DateTime.Now.ToString("yy0MM") + "01";

            if (!string.IsNullOrWhiteSpace(maxGoodsCode))
            {
                //获取最大的商品编码是否是当月的,2400601其中06是月份
                var maxGoodsCodeMonth = maxGoodsCode.Substring(3, 2);
                var nowMonth = DateTime.Now.ToString("MM");
                if (maxGoodsCodeMonth == nowMonth)
                {

                    int num = Convert.ToInt32(maxGoodsCode);
                    num++;
                    goodsCode = "P" + num.ToString();//DateTime.Now.ToString("yy0MM") + num.ToString().PadLeft(2, '0');

                }
            }


            codes.GoodsCode = goodsCode;
            codes.BillType = 1;
            codes.CreateTime = DateTime.Now;
            codeDal.Insert(codes);

            return codes;
        }

        /// <summary>
        /// 编辑商品入库单
        /// </summary>
        /// <param name="lKWarehouseEntry"></param>
        /// <returns></returns>
        public bool EditLKWarehouseEntry(LKWarehouseEntryDto lKWarehouseEntryDto)
        {
            var lKWarehouseEntry = lKWarehouseEntryDto.WarehouseEntry;
            var cus = dal.Get(lKWarehouseEntry.Id);
            if (cus == null)
            {
                return false;
            }
            if (cus.CompanyId != UserContext.CompanyId) return false;
            lKWarehouseEntry.BillNo = cus.BillNo;
            lKWarehouseEntry.CreateTime = cus.CreateTime;
            lKWarehouseEntry.CreateUserId = cus.CreateUserId;
            lKWarehouseEntry.CreateUser = cus.CreateUser;
            lKWarehouseEntry.ModifyUserId = LoginHelper.GetUserId();
            lKWarehouseEntry.ModifyUser = LoginHelper.UserName();
            lKWarehouseEntry.ModifyTime = DateTime.Now;
            lKWarehouseEntry.CompanyId = UserContext.CompanyId;
            var result = dal.EditLKWarehouseEntry(lKWarehouseEntryDto);//dal.Update(lKWarehouseEntry);

            if (result && lKWarehouseEntryDto.AttachmentId > 0)
            {
                attachmentBll.DeleteLKAttachment(lKWarehouseEntryDto.WarehouseEntry.BillNo);
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = lKWarehouseEntryDto.AttachmentId,
                    BillNo = lKWarehouseEntryDto.WarehouseEntry.BillNo,
                    BillType = (int)BillTypeTemplate.WarehouseEntry,
                });
            }

            return result;
        }


        /// <summary>
        /// 确认入库
        /// </summary>
        /// <param name="id"></param>
        /// <param name="contractNo"></param>
        /// <param name="contractType"></param>
        /// <returns></returns>
        public bool ConfirmLKWarehouseEntry(int id, string contractNo, int contractType)
        {
            return dal.ConfirmLKWarehouseEntry(id, contractNo, contractType);
        }

        /// <summary>
        /// 删除商品入库单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnModel DeleteLKWarehouseEntry(int id)
        {
            var bill = dal.Get(id);
            if (bill == null) return new ReturnModel { Success = false, Msg = "入库单不存在" };
            if (bill.CompanyId != UserContext.CompanyId) return new ReturnModel { Success = false, Msg = "无权限删除" };
            if(bill.IsReview) return new ReturnModel { Success = false, Msg = "已复核的入库单不能删除" };
            if(bill.Status==(int)EntryBillStatus.Confirmed) return new ReturnModel { Success = false, Msg = "已确认的入库单不能删除" };

            var result= dal.DeleteLKWarehouseEntry(id);//DeleteById(id);
            if (result)
            {
                attachmentBll.DeleteLKAttachment(bill.BillNo);
            }
            return new ReturnModel { Success = result, Msg = result ? "删除成功" : "删除失败" };
        }

        /// <summary>
        /// 获取商品入库单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LKWarehouseEntryDto GetLKWarehouseEntryById(int id)
        {
            var bill = dal.Get(id);
            if (bill.CompanyId != UserContext.CompanyId)
                return new LKWarehouseEntryDto();


            var detailList = detailDal.GetListByWhere("EntryId=@id", new { id }).ToList();
            var costList = costDal.GetListByWhere("EntryId=@id", new { id }).ToList();

            var attachment = attachmentBll.GetLKAttachmentView(bill.BillNo);
            return new LKWarehouseEntryDto { WarehouseEntry = bill, Details = detailList, Costs = costList, FilePath = attachment?.AttachmentName, FileName = attachment?.OriginalName };
        }

        public List<LKWarehouseEntryDetail> GetLKWarehouseEntryDetails(int id)
        {
            return dal.GetKWarehouseEntryDetails(id);
        }

        /// <summary>
        /// 根据客户编号获取商品入库单明细
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public List<LKWarehouseEntryDetail> GetLKWarehouseEntryDetailsByCustomerId(int customerId)
        {
            return dal.GetLKWarehouseEntryDetailsByCustomerId(customerId);
        }

        //复核入库单
        public bool ReviewLKWarehouseEntry(int id)
        {
            var bill = dal.Get(id);
            if (bill == null) return false;
            if (bill.CompanyId != UserContext.CompanyId) return false;
            bill.IsReview = true;
            bill.Status = (int)EntryBillStatus.Confirmed;
            bill.ReviewerId = LoginHelper.GetUserId();
            bill.Reviewer = LoginHelper.UserName();
            bill.ReviewTime = DateTime.Now;

            return dal.Update(bill);
        }
    }
}

